//
//  DownloadHomeViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/5/21.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let downloadListCellIdentifier = "DownloadListCell"
private let downloadingCellIdentifier = "DownloadingCell"
private let noDataCellIdentifier = "NoDataTableCell"

class DownloadHomeViewController: BaseViewController {

  enum ContentType {
    case downloaded, downloading
  }
  
  struct DownloadedAlbum {
    var album: Album
    var downloadedAudios: [Audio]?
  }
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var tableView: UITableView!
  
  // MARK: - Private vars
  
  private var downloadedAlbums: [DownloadedAlbum]?
  private var selectedAlbumID = -1
  
  // MARK: - Private methods
  
  private func prepareUI() {
    tableView.register(UINib(nibName: noDataCellIdentifier, bundle: nil), forCellReuseIdentifier: noDataCellIdentifier)
  }
  
  private func loadData() {
    if let albums = AudioDownloadManager.shared.getAllAlbumsHaveDownloadedAudios() {
      let downloadedAlbums: [DownloadedAlbum] = albums.map {
        let downloadedAlbum = DownloadedAlbum (
          album: $0,
          downloadedAudios: $0.downloadedAudios
        )
        return downloadedAlbum
      }
      self.downloadedAlbums = downloadedAlbums
    } else {
      self.downloadedAlbums = nil
    }
    tableView.reloadData()
  }
  
  private func getTotalFileSizeText() -> String {
    var totalFileSize: Float = 0
    downloadedAlbums?.forEach {
      totalFileSize += $0.album.downloadedAudioFileSizeInMegaBytes
    }
    if totalFileSize == 0 {
      return ""
    } else {
      return "共\(String(format: "%.1f", totalFileSize))M"
    }
  }
  
  private func addNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(downloadFinished(notifiation:)), name: .downloadFinished, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(streamingCacheFinished), name: .streamingCacheFinished, object: nil)
  }
  
  @objc private func downloadFinished(notifiation: Notification) {
    loadData()
  }
  
  @objc private func streamingCacheFinished() {
    loadData()
  }
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    addNotifications()
    loadData()
    prepareUI()
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowDownloadAlbumDetailSegue" {
      if selectedAlbumID >= 0 {
        let albumDetailViewController = segue.destination as! DownloadDetailViewController
        albumDetailViewController.albumIdentifier = selectedAlbumID
        selectedAlbumID = -1
      }
    }
  }
  
  deinit {
    NotificationCenter.default.removeObserver(self)
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  
}

// MARK: - UITableViewDataSource

extension DownloadHomeViewController: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    return 1
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let count = downloadedAlbums?.count, count > 0 {
      return count + 1
    } else {
      return 2
    }
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
      // downloading cell
      let cell = tableView.dequeueReusableCell(withIdentifier: downloadingCellIdentifier, for: indexPath) as! DownloadingCell
      let downloadingCount = AudioDownloadManager.shared.getDownloadingAudiosCount()
      if downloadingCount > 0 {
        cell.downloadingLabel.text = "\(downloadingCount)个节目正在下载"
        cell.selectionStyle = .default
        cell.rightArrow.isHidden = false
      } else {
        cell.downloadingLabel.text = "没有正在下载的内容"
        cell.selectionStyle = .none
        cell.rightArrow.isHidden = true
      }
      return cell
    } else {
      if let count = downloadedAlbums?.count, count > 0 {
        // downloaded cell
        let cell = tableView.dequeueReusableCell(withIdentifier: downloadListCellIdentifier, for: indexPath) as! DownloadListCell
        if let downloadAlbum = downloadedAlbums?[indexPath.row - 1] {
          var audioCount = 0
          if let count = downloadAlbum.album.downloadedAudios?.count {
            audioCount = count
          }
          cell.prepare (
            album: downloadAlbum.album,
            totalFileSize: downloadAlbum.album.downloadedAudioFileSizeInMegaBytes,
            downloadedCount: audioCount
          )
        }
        
        return cell
      } else {
        // no data cell
        let cell = tableView.dequeueReusableCell(withIdentifier: noDataCellIdentifier, for: indexPath) as! NoDataTableCell
        cell.tipLabel.text = "没有下载内容"
        return cell
      }
    }
  }
  
  func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return getTotalFileSizeText()
  }
}

// MARK: - UITableViewDelegate

extension DownloadHomeViewController: UITableViewDelegate {
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
      // show downloading
      let downloadingCount = AudioDownloadManager.shared.getDownloadingAudiosCount()
      if downloadingCount > 0 {
        performSegue(withIdentifier: "ShowDownloadingSegue", sender: nil)
      }
    } else {
      // show album detail
      if let album = downloadedAlbums?[indexPath.row - 1].album {
        selectedAlbumID = Int(album.id)
        performSegue(withIdentifier: "ShowDownloadAlbumDetailSegue", sender: nil)
      }
    }
    
    tableView.deselectRow(at: indexPath, animated: true)
  }

  func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return indexPath.row > 0
  }

  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
      if downloadedAlbums != nil {
        let downloadAlbum = downloadedAlbums![indexPath.row - 1]
        let album = downloadAlbum.album
        album.audios?.forEach {
          $0.removeCachedfile()
        }
        downloadedAlbums!.remove(at: indexPath.row - 1)
//        tableView.deleteRows(at: [indexPath], with: .automatic)
        tableView.reloadData()
      }
    }
  }
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 0 {
      // downloading cell
      return DownloadingCell.defaultHeight
    } else {
      if let count = downloadedAlbums?.count, count > 0 {
        return DownloadListCell.defaultHeight
      } else {
        return NoDataTableCell.defaultHeight
      }
    }
  }
}
